package models

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var DB *gorm.DB

func init() {
	var err error
	dsn := "root:root@tcp(127.0.0.1:3306)/blog?charset=utf8mb4&parseTime=True&loc=Local"
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(err)
	}
	DB.AutoMigrate(&CarTypes{})
}

type CarTypes struct {
	gorm.Model
	Title string      `gorm:"varchar(255);not null;comment:类型名称"`
	Pid   int         `gorm:"int(11);comment:父级id"`
	Cars  []*CarTypes `gorm:"foreignKey:Pid"`
}

func GetCarTypeAll(pid uint) ([]*CarType, error) {
	var CarList []*CarType
	err := DB.Where("pid = ?", pid).Preload("Cars").Find(&CarList).Error
	if err != nil {
		return CarList, err
	}
	for _, v := range CarList {
		list, err := GetCarTypeAll(v.ID)
		if err != nil {
			return CarList, err
		}
		v.Cars = list
	}

	return CarList, nil
}

type CarType struct {
	gorm.Model
	Title string     `gorm:"varchar(255);not null;comment:类型名称"`
	Pid   int        `gorm:"int(11);comment:父级id"`
	Cars  []*CarType `gorm:"foreignKey:Pid"`
}
